<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="班级名称" prop="clazzName">
          <el-input v-model="queryParams.clazzName" placeholder="请输入班级名称" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="建班时间" prop="startTime">
          <el-date-picker v-model="queryParams.startTime" type="date" placeholder="选择建班时间"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:clazz:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:clazz:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:clazz:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:clazz:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" />
        <el-table-column label="班级名称"  align="center" prop="clazzName" :show-overflow-tooltip="true" />
        <el-table-column label="建班时间"  align="center" prop="startTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:clazz:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:clazz:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="handleAssignCourses(scope.row)"
              v-hasPermi="['system:clazz:assignCourses']"
            >分配课程</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination  v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="班级名称" prop="clazzName">
                <el-input v-model="form.clazzName" placeholder="请输入班级名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="建班时间" prop="startTime">
                <el-date-picker v-model="form.startTime" type="date" placeholder="选择建班时间"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 分配课程对话框 -->
      <el-dialog :title="coursesTitle" :visible.sync="coursesOpen" width="800px" append-to-body>
        <el-form ref="coursesForm" :model="coursesForm" :rules="coursesFormRules" label-width="120px">
          <!-- <el-tabs v-model="activeTab" @tab-click="handleClick">
            <el-tab-pane v-for="(i,j) in termList" :key="j" :label="i.termName" :name="String(i.id)">{{ i.termName }}</el-tab-pane>
          </el-tabs> -->
          <el-select v-model="activeTab" style="margin-bottom: 20px;" placeholder="请选择所属学期" @change="handleClick">
            <el-option 
              v-for="item in termList" 
              :key="item.id"
              :label="item.termName"
              :value="item.id"
            />
          </el-select>
          <template>
            <el-transfer
              v-model="coursesForm.courseIds"
              filterable
              :titles="['可选课程', '已选课程']"
              :button-texts="['取消' , '选择']"
              :data="coursesdDataList">
              <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>
            </el-transfer>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="coursesSubmit" v-if="coursesForm.courseIds.length > 0">确 定</el-button>
          <el-button @click="coursesCancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listClazz, getClazz, delClazz, addClazz, updateClazz, getCoursesdList,setClazzCourses, getAssignCoursesdList } from "@/api/teachMan/clazz";
  import { termList } from "@/api/student";

  import Crontab from '@/components/Crontab'
  export default {
    name: "Clazz",
    components: { Crontab },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          clazzName: undefined,
          startTime: undefined,
        },
        // 表单参数
        form: {
          clazzName:null,
          startTime:null,
        },
        // 表单校验
        rules: {
          clazzName: [
            { required: true, message: "班级名称不能为空", trigger: "blur" }
          ],
          startTime: [
            { required: true, message: "建班时间不能为空", trigger: "blur" }
          ],
        },
        // 分配课程
        coursesOpen: false,
        coursesTitle: '',
        termList: [],
        // activeTab: '',
        activeTab: null,
        coursesdDataList: [],
        coursesForm: {
          clazzId:null,
          courseIds: []
        },
        coursesFormRules:{
          courseIds:[
            { required: true, message: "所选课程不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        listClazz(this.queryParams).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {   
          clazzName: undefined,
          startTime: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加任务";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getClazz(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改任务";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateClazz(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addClazz(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delClazz(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('monitor/clazz/export', {
          ...this.queryParams
        }, `班级${new Date().getTime()}.xlsx`)
      },
       // 点击分配课程按钮
      async handleAssignCourses(row){
        this.resetForm("coursesForm");
        this.coursesOpen = true
        this.coursesForm.clazzId = row.id
        this.coursesTitle = row.clazzName + '分配课程'
        // 获取学期列表
        await termList().then(res=>{
          this.termList = res
        })
        this.coursesdDataList = []
        if (this.termList.length) { 
          this.activeTab = this.termList[0].id
          // this.activeTab = String(this.termList[0].id)
          this.getAssignCoursesd(this.termList[0].id)
        }
        // 已分配课程回显
        console.log(this.coursesForm.courseIds)
      },
      // tab切换时获取所属课程数据
      handleClick(){
        this.coursesdDataList = []
        this.coursesForm.courseIds = []
        // this.activeTab = String(this.activeTab)
        this.getAssignCoursesd(this.activeTab)
      },
      getAssignCoursesd(id){
        let data = {
          clazzId: this.coursesForm.clazzId,
          termId: Number(id)
        }
        // 获取未选择的课程
        getCoursesdList(data).then(res=>{
          if(res.list.length>0){
            res.list.forEach(i=>{
              this.coursesdDataList.push({
                label:i.courseName,
                key:i.id,
                disabled: false 
              })
            })
          }
        })
        // 回显的已选课程数据
        getAssignCoursesdList(data).then(res=>{
          console.log(res,res.list)
          const selected = res.list || [];
          this.coursesForm.courseIds = selected.map(i => i.courseId);
          selected.forEach(item => {
          const exists = this.coursesdDataList.some(c => c.key === item.courseId);
          if (!exists) {
            this.coursesdDataList.push({
              key: item.courseId,
              label: item.courseName,
              disabled: false
            });
          }
        });
        })
      },
      // 分配课程提交
      coursesSubmit(){ 
        if(this.coursesForm.courseIds.length > 0){
          this.coursesForm.termId = Number(this.activeTab)
          let data = []
          this.coursesForm.courseIds.forEach(i=>{
            data.push({
              clazzId: this.coursesForm.clazzId,
              termId: this.coursesForm.termId,
              courseId: i
            })
          })
          setClazzCourses(data).then(res=>{
            this.$modal.msgSuccess("分配成功");
            this.coursesOpen = false
            this.getList();
          })
        }
      },
      // 分配课程取消
      coursesCancel(){
        this.coursesOpen = false
        this.coursesdDataList = []
        this.coursesForm = {   
          clazzId: null,
          termId: null,
          courseIds: []
        };
        this.resetForm("coursesForm");
      },
    }
  };
</script>

<style>
  .el-input--medium .el-input__inner{
    width: 260px;
  }
</style>